using CriWare;
using IQIGame.Onigao.Framework;
using IQIGame.Onigao.Game.Assets.Scripts.Main.Runtime.Media;
using System.Collections.Generic;
using UnityEngine;

namespace IQIGame.Onigao.Game
{
    /// <summary>
    /// 视频播放管理器，使用示例请看UITestWindow.cs
    /// 请使用Criware的Sofdec2的视频编码器转为VP9编码的.usm格式的视频
    /// Criware的音频和视频是支持加密的。
    /// </summary>
    public class VideoManager : FrameMonoModule
    {
        Transform m_rootTransform;
        GameObject m_rootGameObject;

        public const int VideoPlayerPoolCount = 3;
        private readonly Dictionary<int, Stack<VideoPlayerForUI>> _videoPlayerForUIPool = new Dictionary<int, Stack<VideoPlayerForUI>>();
        private readonly Dictionary<int, Stack<VideoPlayerForRender>> _videoPlayerForRenderPool = new Dictionary<int, Stack<VideoPlayerForRender>>();

        private List<VideoPlayerBase> _videoPlayers = new List<VideoPlayerBase>();

        protected override void OnInit()
        {
            FrameworkEntry.MonoDriver.updateEvent += OnUpdate;
            //需要在AudioManager之后初始化
            var criAtom = UnityEngine.Object.FindObjectOfType<CriAtom>();
            if (criAtom != null)
            {
                m_rootGameObject = new GameObject("MovieManager");
                m_rootTransform = m_rootGameObject.transform;
                m_rootTransform.transform.SetParent(criAtom.transform, false);
            }
            else
            {
                LogGame.LogError("CriAtom 没有初始化，请检查！");
            }

        }

        protected override void OnShutdown()
        {
            FrameworkEntry.MonoDriver.updateEvent -= OnUpdate;
        }

        protected override void OnEnterGame()
        {

        }


        private void OnUpdate(float deltaTime, float unscaleDeltaTime)
        {
            for (int i = 0; i < _videoPlayers.Count; i++)
            {
                var player = _videoPlayers[i];
                player.OnUpdate(deltaTime);
                if (player.needReturnPool && player.IsPlayerEnd)
                {
                    ReturnPlayer(player);
                    _videoPlayers.RemoveAt(i);
                    --i;
                }
            }
        }

        // 回收
        protected void ReturnPlayer(VideoPlayerBase player)
        {
            var key = GetVideoTypeKey(player.ApplyTargetAlpha, player.AdditiveMode);
            switch (player)
            {
                case VideoPlayerForUI videoPlayerForUI:
                    if (!_videoPlayerForUIPool.TryGetValue(key, out var pool))
                    {
                        pool = new Stack<VideoPlayerForUI>();
                        _videoPlayerForUIPool.Add(key, pool);
                    }
                    if (pool.Count < VideoPlayerPoolCount)
                    {
                        videoPlayerForUI.OnReset();
                        pool.Push(videoPlayerForUI);
                        return;
                    }
                    break;
                case VideoPlayerForRender videoPlayerForRender:
                    if (!_videoPlayerForRenderPool.TryGetValue(key, out var pool2))
                    {
                        pool2 = new Stack<VideoPlayerForRender>();
                        _videoPlayerForRenderPool.Add(key, pool2);
                    }
                    if (pool2.Count < VideoPlayerPoolCount)
                    {
                        videoPlayerForRender.OnReset();
                        pool2.Push(videoPlayerForRender);
                        return;
                    }
                    break;
            }
            player.Dispose();
            LogGame.Log($"{nameof(VideoManager)}回收视频播放器超过最大数量{VideoPlayerPoolCount}，直接销毁");
        }

        public int GetVideoTypeKey(bool isApplyTargetAlpha, bool additiveMode)
        {
            var key = 0;
            if (isApplyTargetAlpha)
            {
                key |= 0b1;
            }
            if (additiveMode)
            {
                key |= 0b10;
            }
            return key;
        }

        /// <summary>
        /// 获取一个VideoPlayer，使用UI显示
        /// </summary>
        /// <param name="isApplyTargetAlpha"></param>
        /// <param name="additiveMode"></param>
        /// <returns></returns>
        public VideoPlayerForUI GetVideoPlayerForUI(bool isApplyTargetAlpha = false, bool additiveMode = false)
        {
            var key = GetVideoTypeKey(isApplyTargetAlpha, additiveMode);
            if (!_videoPlayerForUIPool.TryGetValue(key, out var pool))
            {
                pool = new Stack<VideoPlayerForUI>();
                _videoPlayerForUIPool.Add(key, pool);
            }
            VideoPlayerForUI player = null;
            if (pool.Count > 0)
            {
                player = pool.Pop();
            }
            else
            {
                player = new VideoPlayerForUI();
            }
            _videoPlayers.Add(player);
            player.InitPlayer(m_rootTransform, isApplyTargetAlpha, additiveMode);
            return player;
        }

        /// <summary>
        /// 获取一个VideoPlayer,使用Render显示
        /// </summary>
        /// <param name="isApplyTargetAlpha"></param>
        /// <param name="additiveMode"></param>
        /// <returns></returns>
        public VideoPlayerForRender GetVideoPlayerForRender(bool isApplyTargetAlpha = false, bool additiveMode = false)
        {
            var key = GetVideoTypeKey(isApplyTargetAlpha, additiveMode);
            if (!_videoPlayerForRenderPool.TryGetValue(key, out var pool))
            {
                pool = new Stack<VideoPlayerForRender>();
                _videoPlayerForRenderPool.Add(key, pool);
            }
            VideoPlayerForRender player = null;
            if (pool.Count > 0)
            {
                player = pool.Pop();
            }
            else
            {
                player = new VideoPlayerForRender();
            }
            _videoPlayers.Add(player);
            player.InitPlayer(m_rootTransform, isApplyTargetAlpha, additiveMode);
            return player;
        }



    }
}
